﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using HIWSystem.Common;
using HIWSystem.Models;
using System;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace HIWSystem.ViewModel
{
    public class SnFormatDefineViewModel : ViewModelBase
    {
        #region 属性

        private string customerCode;

        /// <summary>
        /// 客户代码
        /// </summary>
        public string CustomerCode
        {
            get { return customerCode; }
            set { customerCode = value; this.RaisePropertyChanged(() => CustomerCode); }
        }

        private ObservableCollection<string> yearSections;

        /// <summary>
        /// 年部分选项集合
        /// </summary>
        public ObservableCollection<string> YearSections
        {
            get { return yearSections; }
            set { yearSections = value; this.RaisePropertyChanged(() => YearSections); }
        }

        private string yearSection;

        /// <summary>
        /// 选择的年部分
        /// </summary>
        public string YearSection
        {
            get { return yearSection; }
            set { yearSection = value; this.RaisePropertyChanged(() => YearSection); }
        }

        private ObservableCollection<string> monthSections;

        /// <summary>
        /// 月部分选项集合
        /// </summary>
        public ObservableCollection<string> MonthSections
        {
            get { return monthSections; }
            set { monthSections = value; this.RaisePropertyChanged(() => MonthSections); }
        }

        private string monthSection;

        /// <summary>
        /// 选择的年部分
        /// </summary>
        public string MonthSection
        {
            get { return monthSection; }
            set { monthSection = value; this.RaisePropertyChanged(() => MonthSection); }
        }

        private ObservableCollection<string> weekSections;

        /// <summary>
        /// 周部分选项集合
        /// </summary>
        public ObservableCollection<string> WeekSections
        {
            get { return weekSections; }
            set { weekSections = value; this.RaisePropertyChanged(() => WeekSections); }
        }

        private string weekSection;

        /// <summary>
        /// 选择的周部分
        /// </summary>
        public string WeekSection
        {
            get { return weekSection; }
            set { weekSection = value; this.RaisePropertyChanged(() => WeekSection); }
        }

        private ObservableCollection<string> weekDaySections;

        /// <summary>
        /// 星期部分集合
        /// </summary>
        public ObservableCollection<string> WeekDaySections
        {
            get { return weekDaySections; }
            set { weekDaySections = value; this.RaisePropertyChanged(() => WeekDaySections); }
        }

        private string weekDaySectio;

        /// <summary>
        /// 选择的星期部分
        /// </summary>
        public string WeekDaySection
        {
            get { return weekDaySectio; }
            set { weekDaySectio = value; this.RaisePropertyChanged(() => WeekDaySection); }
        }

        private ObservableCollection<string> daySections;

        /// <summary>
        /// 日部分集合
        /// </summary>
        public ObservableCollection<string> DaySections
        {
            get { return daySections; }
            set { daySections = value; this.RaisePropertyChanged(() => DaySections); }
        }

        private string daySection;

        /// <summary>
        /// 选择的日部分
        /// </summary>
        public string DaySection
        {
            get { return daySection; }
            set { daySection = value; this.RaisePropertyChanged(() => DaySection); }
        }

        private string PNcode;

        /// <summary>
        /// 机种代码
        /// </summary>
        public string PNCode
        {
            get { return PNcode; }
            set { PNcode = value; this.RaisePropertyChanged(() => PNCode); }
        }

        private ObservableCollection<string> serialNumberSections;

        /// <summary>
        /// 流水码部分集合
        /// </summary>
        public ObservableCollection<string> SerialNumberSections
        {
            get { return serialNumberSections; }
            set { serialNumberSections = value; this.RaisePropertyChanged(() => SerialNumberSections); }
        }

        private string serialNumberSection;

        /// <summary>
        /// 选择的流水码
        /// </summary>
        public string SerialNumberSection
        {
            get { return serialNumberSection; }
            set { serialNumberSection = value; this.RaisePropertyChanged(() => SerialNumberSection); }
        }

        private string serialNumberDigit;

        /// <summary>
        /// 流水码位数
        /// </summary>
        public string SerialNumberDigit
        {
            get { return serialNumberDigit; }
            set { serialNumberDigit = value; this.RaisePropertyChanged(() => SerialNumberDigit); }
        }
        private ObservableCollection<string> componentColumnNames;
        /// <summary>
        /// 序列号格式组件列名
        /// </summary>
        public ObservableCollection<string> ComponentColumnNames
        {
            get { return componentColumnNames; }
            set { componentColumnNames = value; this.RaisePropertyChanged(() => ComponentColumnNames); }
        }
        private ObservableCollection<string> componentSequences;
        /// <summary>
        /// 序列号格式组件顺序
        /// </summary>
        public ObservableCollection<string> ComponentSequences
        {
            get { return componentSequences; }
            set { componentSequences = value; this.RaisePropertyChanged(() => ComponentSequences); }
        }

        #endregion 属性

        #region 命令

        private RelayCommand confirmCmd;

        public RelayCommand ConfirmCmd
        {
            get
            {
                confirmCmd = confirmCmd ?? new RelayCommand(Confirm);
                return confirmCmd;
            }
            set { confirmCmd = value; }
        }

        private RelayCommand cancelCmd;

        public RelayCommand CancelCmd
        {
            get
            {
                cancelCmd = cancelCmd ?? new RelayCommand(Cancel);
                return cancelCmd;
            }
            set { cancelCmd = value; }
        }

        private RelayCommand loadedPageCmd;

        public RelayCommand LoadedPageCmd
        {
            get
            {
                loadedPageCmd = loadedPageCmd ?? new RelayCommand(LoadedPage);
                return loadedPageCmd;
            }
            set { loadedPageCmd = value; }
        }
        private RelayCommand autoGeneratePNCodeCmd;

        public RelayCommand AutoGeneratePNCodeCmd
        {
            get {
                autoGeneratePNCodeCmd = autoGeneratePNCodeCmd ?? new RelayCommand(AutoGeneratePNCode);
                return autoGeneratePNCodeCmd; }
            set { autoGeneratePNCodeCmd = value; }
        }
        private RelayCommand<string> lstComponentColumnName_MouseDoubleClick;

        public RelayCommand<string> LstComponentColumnName_MouseDoubleClick
        {
            get {
                lstComponentColumnName_MouseDoubleClick = lstComponentColumnName_MouseDoubleClick ??
                    new RelayCommand<string>(LstComponentColumnNameMouseDoubleClickHandler);
                return lstComponentColumnName_MouseDoubleClick; }
            set { lstComponentColumnName_MouseDoubleClick = value; }
        }
        private RelayCommand<string> lstComponentSequence_MouseDoubleClick;

        public RelayCommand<string> LstComponentSequence_MouseDoubleClick
        {
            get {
                lstComponentSequence_MouseDoubleClick = lstComponentSequence_MouseDoubleClick ??
                    new RelayCommand<string>(LstComponentSequenceMouseDoubleClickHandler);
                return lstComponentSequence_MouseDoubleClick; }
            set { lstComponentSequence_MouseDoubleClick = value; }
        }
        #endregion 命令

        #region 方法

        /// <summary>
        /// 页面加载
        /// </summary>
        private void LoadedPage()
        {
            OnLoadingPage();
        }

        private async Task OnLoadingPage()
        {
            await Task.Run(() =>
            {
                Application.Current.Dispatcher.BeginInvoke((Action)(() =>
                {
                    //初始化相关参数
                    YearSections = new ObservableCollection<string>() { "--请选择--", "YY", "YYYY" };
                    MonthSections = new ObservableCollection<string>() { "--请选择--", "M", "MM" };
                    WeekSections = new ObservableCollection<string>() { "--请选择--", "W", "WW" };
                    WeekDaySections = new ObservableCollection<string>() { "--请选择--", "X" };
                    DaySections = new ObservableCollection<string>() { "--请选择--", "D", "DD" };
                    SerialNumberSections = new ObservableCollection<string>() { "--请选择--", "?", "33" };
                    //初始化组件列表
                    ComponentColumnNames = new ObservableCollection<string>() { 
                        "客户代码_CustomerCode",
                        "年部分_YearSection", 
                        "月部分_MonthSection",
                        "周别部分_WeekSection",
                        "星期几部分_WeekDaySection",
                        "天部分_DaySection",
                        "机种代码_PNCode",
                    };
                }));
            });
        }

        /// <summary>
        /// 确认
        /// </summary>
        private void Confirm()
        {
            try
            {
                //判断流水码位数填写的是不是数字
                bool isNumber = false;
                isNumber= BusinessProcess.IsNumber(SerialNumberDigit??"");
                if (!isNumber)
                {
                   MessageBox.Show("流水码的位数填写的不是数字,请重新填写!","软件温馨提示!",MessageBoxButton.OK,MessageBoxImage.Warning);
                    return;
                }
                if (SerialNumberSection=="--请选择--" || (SerialNumberSection??"")=="")
                {
                    MessageBox.Show("流水码没有选择有效值!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                if (ComponentSequences.Count==0)
                {
                    MessageBox.Show("没有添加序列号格式组件顺序，请先添加再点确认!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                SnFormatEntity entity = new SnFormatEntity
                {
                    CustomerCode = this.CustomerCode ?? "",
                    YearSection = this.YearSection == "--请选择--" ? "" : this.YearSection ?? "",
                    MonthSection = this.MonthSection == "--请选择--" ? "" : this.MonthSection ?? "",
                    WeekSection = this.WeekSection == "--请选择--" ? "" : this.WeekSection ?? "",
                    WeekDaySection = this.WeekDaySection == "--请选择--" ? "" : this.WeekDaySection ?? "",
                    DaySection = this.DaySection == "--请选择--" ? "" : this.DaySection ?? "",
                    PNCode = this.PNCode ?? "",
                    SerialNumber = this.SerialNumberSection == "--请选择--" ? "" : this.SerialNumberSection ?? "",
                    SerialNumberDigit = this.SerialNumberDigit ?? ""
                };
                StringBuilder SnFormat = new StringBuilder();
                StringBuilder strComponentSequence = new StringBuilder();
                int currentSnFormatLength = 1;//当前序列号位置
                for (int i = 0; i < ComponentSequences.Count; i++)
                {
                    var type = entity.GetType();
                    var property = type.GetProperty(ComponentSequences[i].Split('_')[1]);
                    if (property == null)
                    {
                        MessageBox.Show("顺序列表里的组件【" + ComponentSequences[i].Split('_')[0] + "】在上面未找到", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    var propertyValue = property.GetValue(entity);
                    if (propertyValue.ToString() == "")
                    {
                        MessageBox.Show("顺序列表已经选中该组件【" + ComponentSequences[i].Split('_')[0] + "】但是上面没有输入或者选择值,其值为空", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    //计算每个组件在整个序列号里面的起始和结束位置
                    property = type.GetProperty(string.Format($"{ComponentSequences[i].Split('_')[1]}StartIndex"));//CustomerCodeStartIndex
                    property.SetValue(entity, currentSnFormatLength);//起始位置
                    currentSnFormatLength += propertyValue.ToString().Length;//加上组件自身的长度，即结束位置
                    property = type.GetProperty(string.Format($"{ComponentSequences[i].Split('_')[1]}StopIndex"));//CustomerCodeStopIndex
                    property.SetValue(entity, currentSnFormatLength);//结束位置
                    //不加分隔符的情况1.集合里面只有一个元素时 2.循环到最后一个
                    if (i + 1 == ComponentSequences.Count || ComponentSequences.Count==1) 
                    {
                        strComponentSequence.Append(ComponentSequences[i].Split('_')[1]);
                    }
                    else
                    {
                        strComponentSequence.Append(ComponentSequences[i].Split('_')[1] + "|");
                    }
                    SnFormat.Append(propertyValue.ToString());
                }
                if (SnFormat.ToString()=="")
                {
                    MessageBox.Show("序列号格式不能为空!", "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                SnFormat.Append(entity.SerialNumber); //单独加上流水码定义部分，这个不放在组件列表里面是为了序列号结构的统一，统一将流水码放在最后。
                bool isExists = BusinessProcess.IsSnFormatExists(SnFormat.ToString());
                if (isExists)
                {
                    MessageBox.Show(string.Format("此序列号格式｛0｝在系统中已经存在!",SnFormat),"软件温馨提示!",MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                //单独添加流水号组件在整个序列号格式中的起始和结束位置
                entity.SerialNumberStartIndex = currentSnFormatLength;
                entity.SerialNumberStopIndex = currentSnFormatLength + Convert.ToInt32(entity.SerialNumberDigit);
                ComponentSequences = new ObservableCollection<string>(); //清空组件顺序表中的数据，防止保留原始数据。
                entity.ComponentSequence = strComponentSequence.ToString();
                Messenger.Default.Send<SnFormatEntity>(entity, "SnFormatDefine");
                ViewManager.Close("SnFormatDefine");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 取消
        /// </summary>
        private void Cancel()
        {
            ViewManager.Close("SnFormatDefine");
        }
        /// <summary>
        /// 自动生成机种代码《只针对于HIW内部序列号》
        /// </summary>
        private void AutoGeneratePNCode()
        {
            if (CustomerCode == "HIW")
            {
                string SNFormat = BusinessProcess.GenerateSnFormat("滤波器");
                PNCode = SNFormat.Substring(7, 3);//HIW23254AAD?????
            }
            else
            {
               MessageBox.Show("此功能只针对于HIW开头的内部序列号","软件温馨提示!",MessageBoxButton.OK,MessageBoxImage.Warning);
                return;
            }
        }

        private void LstComponentColumnNameMouseDoubleClickHandler(string obj)
        {
            if (ComponentSequences is null)
                ComponentSequences = new ObservableCollection<string>();
            if (!ComponentSequences.Contains(obj))
                ComponentSequences.Add(obj);
        }

        private void LstComponentSequenceMouseDoubleClickHandler(string obj)
        {
            ComponentSequences.Remove(obj);
        }
        #endregion 方法
    }
}